package com.xunmall.base.util.password;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Properties;

import com.xunmall.base.util.security.EncryptUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

/**
 * @Author: WangYanjing
 * @Date: 2018/12/27 10:53
 * @Description:
 */
@Component
public class PasswordManager {
	private ArrayList<String> passwords = new ArrayList<String>();
	
	private String password_path;
	
	private String root_sec;
	
	public PasswordManager(String password_path, String root_sec) {
		this.password_path = password_path;
		this.root_sec = root_sec;
		loadPassword();
	}
	

	private void loadPassword() {
		//读取security properties
		Properties passProp = new  Properties();  
		try  {    
    		if (!StringUtils.isEmpty(password_path)) {
    			InputStream passIn;
    			if (password_path.startsWith("classpath:")) {
    				String passwd_file = password_path.substring(10);
    				passIn = getClass().getClassLoader().getResourceAsStream(passwd_file);
    			} else {
    				passIn = new FileInputStream(password_path);
    			}
				passProp.load(passIn);
    			
    			String pwd;
        		int last_version = 1;
    			do {
	    			pwd = passProp.getProperty("password."+last_version);
	    			if (pwd != null) {
	    				passwords.add(EncryptUtils.decrypt(pwd, root_sec));
	    				last_version++;
	    			}
	    		} while (pwd != null);

    		}
    		
        }  catch  (IOException e) {    
            e.printStackTrace();    
        }  
	}
	
	public String getPassword(int version) {
		if (version <= 0 || version > passwords.size()) {
            return null;
        }
		return passwords.get(version-1);
	}
	
	public int getLastestPasswordVersion() {
		return passwords.size();
	}
	
	public String getPassword() {
		int ver = getLastestPasswordVersion();
		return getPassword(ver);
	}
	
    public static void main(String[] args) {
    	System.out.println(EncryptUtils.encrypt("", ""));
    }

}
